package com.iss.umservice.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Init extends HttpServlet
{
    private static final long serialVersionUID = -882594609827435062L;
    
    private static final Logger log = Logger.getLogger(Init.class);
    
    /**
     * Destruction of the servlet. <br>
     */
    public void destroy()
    {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }
    
    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }
    
    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }
    
    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException
    {
        String validDateJiaMi = XmlConfig.newInstance()
                .getModuleNodeValue("system.validDate");
        String validDate = null;
        try
        {
            validDate = RSAEncript.den(validDateJiaMi, "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJC+KNjfLkitykf3/gFitwoWF9iiI/wP2st4vaK6zmj3ScO18fjncBVksTLuj0SJUaQEfV0GW73PdqUyJB9Ot6K243g2CpOghylRi+GE/FobD4mnbPBr2yPrxkxyKZThHJh/bsB2q6qvZRhm7DTZgBV1JGObRUV3qWkVMnzc4jHPAgMBAAECgYBdnwIgtMrlK7QJNPjQwJ8QIRYvg0CvSzoEHgba+OWFs128/zSSAHDZBZYwEWoNtJxf8J99yh0Q+t4NIA+JSIsx8CH4SeawbGchykpzkrEWniVobQ6otgNvIHmw0I5di/Tgn/wKst/Gh0vSS2BxZ8bbfJFwbWXiRFN+OUec6OZ50QJBAOqFdvNwP/VG1utckmUKA54+7/RkGYcHllY9BExniGg2pk09Ov8Y1AVBXa/Nbp/80206SI2Tnwe4fQ/LKzzuOqsCQQCd/8RvPQgsQBpxnAPJEDMaSrVwwRViDbQKw3SO2CbDyxerffLnOQQDIWmstEmAqh5LbTvmxpV6YNMDqlDu6aVtAkB8/e8c5fmgj0XioS8BHOo6wA6BsYwNdJTCl7ifxBpmeKH/zp+P8DqoJmN5XEMWj9hbgdHDayc6JTC6Zy0/RzULAkBSJtbgb/974qjdQZ3GQaIQnZ/RzNNtdGqU3iQQ0dr2Gvdnt8lA6KhpaEol/mfpeord9SIcUE0QoJ+XXEtQrjPRAkEAvwYdqleaNNAgl8TzTpQMdJcAJ4xc2AbnUn9hsBPJKbJUapEne0STUD9ARXMuX3qKr9RL/1bga8FEUGVsy7JDEQ==");
            System.out.println("本软件有效期至：" + validDate);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        Date valid = DateUtil.formdate(validDate, "yyyy-MM-dd");
        if(!valid.after(new Date()))
        {
            this.destroy();
            System.exit(0);
        }
        else
        {
            DateUtil.canrun = true;
        }
    }
    
    public static String getOsName()
    {
        String os = "";
        os = System.getProperty("os.name");
        return os;
    }
    
    public static String getMACAddress()
    {
        String address = "";
        String os = getOsName();
        if (os.startsWith("Windows"))
        {
            try
            {
                String command = "cmd.exe /c ipconfig /all";
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null)
                {
                    if (line.indexOf("Physical Address") > 0)
                    {
                        int index = line.indexOf(":");
                        index += 2;
                        address = line.substring(index);
                        break;
                    }
                }
                br.close();
                return address.trim();
            }
            catch (IOException e)
            {
            }
        }
        else if (os.startsWith("Linux"))
        {
            String command = "/bin/sh -c ifconfig -a";
            Process p;
            try
            {
                p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null)
                {
                    if (line.indexOf("HWaddr") > 0)
                    {
                        int index = line.indexOf("HWaddr") + "HWaddr".length();
                        address = line.substring(index);
                        break;
                    }
                }
                br.close();
            }
            catch (IOException e)
            {
            }
        }
        address = address.trim();
        return address;
    }
}